﻿using Clancy.Interfaces;
using System;
using System.Reactive.Subjects;
using System.Threading.Tasks;

namespace Clancy.Bl
{
    internal class OperationalAdapterProvider : IOperationalAdapterProvider
    {
        private readonly IOperationAdapterFactory m_OperationAdapterFactory;

        private readonly BehaviorSubject<OperationMode> m_OperationModeSubject = new BehaviorSubject<OperationMode>(Interfaces.OperationMode.Undefined);

        public OperationalAdapterProvider(IOperationAdapterFactory operationAdapterFactory)
        {
            m_OperationAdapterFactory = operationAdapterFactory;

            SwitchOperationMode(Interfaces.OperationMode.StandAlone);
        }

        public IOperationAdapter OperationAdapter { get; private set; }

        public IObservable<OperationMode> OperationMode
        {
            get { return m_OperationModeSubject; }
        }

        public Task<bool> SwitchOperationMode(OperationMode mode)
        {
            switch (mode)
            {
                case Interfaces.OperationMode.StandAlone:
                    OperationAdapter = m_OperationAdapterFactory.SwitchToStandAloneMode();
                    break;

                case Interfaces.OperationMode.Online:
                    OperationAdapter = m_OperationAdapterFactory.SwitchToOnlineMode();
                    break;

                default:
                    OperationAdapter.Dispose();
                    OperationAdapter = null;
                    break;
            }
            m_OperationModeSubject.OnNext(mode);

            return Task.FromResult(OperationAdapter != null);
        }
    }
}